package com.xp.flow.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP请求组件
 * 支持GET、POST、PUT、DELETE等HTTP方法的请求处理
 * 
 * @author AI Assistant
 * @since 1.0.0
 */
@Slf4j
@LiteflowComponent("HTTP_REQUEST")
public class HttpRequestComponent extends BaseFlowComponent {

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void process() {
        // 验证必需配置
        validateRequiredConfig("url");
        
        // 获取配置
        String url = getConfigValue("url", "");
        String method = getConfigValue("method", "GET").toUpperCase();
        Integer timeout = getConfigValue("timeout", 30);
        
        logExecution("开始执行HTTP请求: %s %s, 超时: %d秒", method, url, timeout);
        
        // 获取输入数据
        Map<String, Object> inputData = getInputData();
        
        try {
            // 构建请求头
            HttpHeaders headers = buildHeaders(inputData);
            
            // 构建请求体
            Object requestBody = buildRequestBody(method, inputData);
            
            // 创建HTTP实体
            HttpEntity<?> entity = new HttpEntity<>(requestBody, headers);
            
            // 设置超时
            RestTemplate requestTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(timeout))
                .setReadTimeout(Duration.ofSeconds(timeout))
                .build();
            
            // 执行HTTP请求
            ResponseEntity<String> response = executeRequest(url, method, entity, requestTemplate);
            
            // 处理响应
            Map<String, Object> outputData = processResponse(response, inputData);
            
            // 设置输出数据
            setOutputData(outputData);
            
            logExecution("HTTP请求执行成功，状态码: %d", response.getStatusCodeValue());
            
        } catch (Exception e) {
            logError("HTTP请求执行失败: " + url, e);
            
            // 创建错误响应
            Map<String, Object> errorData = new HashMap<>(inputData);
            errorData.put("error", true);
            errorData.put("errorMessage", e.getMessage());
            errorData.put("statusCode", 500);
            
            setOutputData(errorData);
        }
    }
    
    /**
     * 构建请求头
     * 
     * @param inputData 输入数据
     * @return HTTP请求头
     */
    private HttpHeaders buildHeaders(Map<String, Object> inputData) {
        HttpHeaders headers = new HttpHeaders();
        
        // 设置默认Content-Type
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        // 从输入数据中获取自定义请求头
        Object headersObj = inputData.get("headers");
        if (headersObj instanceof Map) {
            Map<String, Object> customHeaders = (Map<String, Object>) headersObj;
            for (Map.Entry<String, Object> entry : customHeaders.entrySet()) {
                headers.add(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        
        return headers;
    }
    
    /**
     * 构建请求体
     * 
     * @param method HTTP方法
     * @param inputData 输入数据
     * @return 请求体
     */
    private Object buildRequestBody(String method, Map<String, Object> inputData) {
        // GET和DELETE方法通常不需要请求体
        if ("GET".equals(method) || "DELETE".equals(method)) {
            return null;
        }
        
        // 从输入数据中获取请求体
        Object body = inputData.get("body");
        if (body != null) {
            return body;
        }
        
        // 如果没有指定body，使用整个输入数据（排除特殊字段）
        Map<String, Object> requestBody = new HashMap<>(inputData);
        requestBody.remove("headers");
        requestBody.remove("metadata");
        
        return requestBody;
    }
    
    /**
     * 执行HTTP请求
     * 
     * @param url 请求URL
     * @param method HTTP方法
     * @param entity HTTP实体
     * @param requestTemplate 请求模板
     * @return 响应结果
     */
    private ResponseEntity<String> executeRequest(String url, String method, HttpEntity<?> entity, RestTemplate requestTemplate) {
        HttpMethod httpMethod = HttpMethod.valueOf(method);
        return requestTemplate.exchange(url, httpMethod, entity, String.class);
    }
    
    /**
     * 处理HTTP响应
     * 
     * @param response HTTP响应
     * @param inputData 原始输入数据
     * @return 处理后的输出数据
     */
    private Map<String, Object> processResponse(ResponseEntity<String> response, Map<String, Object> inputData) {
        Map<String, Object> outputData = new HashMap<>(inputData);
        
        // 设置响应信息
        outputData.put("statusCode", response.getStatusCodeValue());
        outputData.put("headers", response.getHeaders().toSingleValueMap());
        
        // 处理响应体
        String responseBody = response.getBody();
        if (responseBody != null && !responseBody.isEmpty()) {
            try {
                // 尝试解析为JSON
                Object parsedBody = objectMapper.readValue(responseBody, Object.class);
                outputData.put("body", parsedBody);
            } catch (Exception e) {
                // 如果不是JSON，直接存储字符串
                outputData.put("body", responseBody);
            }
        }
        
        // 添加成功标识
        outputData.put("success", response.getStatusCode().is2xxSuccessful());
        
        return outputData;
    }
}